<template>
  <base-modal 
    :title="$t('customer.mergeCustomer.mergeCustomerBtn')" 
    :show.sync="visible" 
    width="1000px" 
    class="merge-customer-dialog"
    @closed="visible = false" 
    >
    <div class="merge-customer-wrap">
      <!--列表合并-->
      <div class="merge-customer-item"  v-if="pageType=='detail'">
        <label>{{$t('customer.mergeCustomer.step1')}}</label>
        <biz-remote-select 
          class="custom-select"
          :field="customerField"
          :is-show-select="true"
          v-model="selectedCustomers"
          :remote-method="searchCustomer"
          :placeholder="$t('common.form.preview.relatedCustomers.pla1')" 
          :computed-width-keys="['name', 'serialNumber']"
          :keyword-length-limit="true"
          multiple
          :multipleLimit="5"
          @input="updateCustomer"
          >
          <div class="customer-template-option" slot="option" slot-scope="{ option }">
            <h3>{{ option.name }}</h3>
            <p>{{ $t('common.base.phone') }}：{{ option.lmPhone }}</p>
            <p>{{ $t('common.base.serialNumber') }}：{{ option.serialNumber }}</p>
          </div>
        </biz-remote-select>
      </div>
      <p class="message" v-if="pageType=='list'">{{$t('customer.mergeCustomer.msg3')}}</p>
      <el-table
        border
        ref="multipleTable"
        :data="selectedCustomers"
        header-row-class-name="base-table-header-v3"
        row-class-name="base-table-row-v3"
        class="customer-select-table"
      >
        <el-table-column  width="40" v-if="pageType=='list'">
          <template slot-scope="scope">
            <el-radio v-model="radioIndex" :label="scope.$index" @change="handleRadioChange(scope.$index, scope.row)"> </el-radio>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          v-for="(column, index) in columns"
          :key="`${column.field}_${index}`"
          :label="column.label"
          :prop="column.field"
          :width="column.width"
          :min-width="column.minWidth "
          :align="column.align"
        >
          <template slot-scope="scope">
            
            <template v-if="column.field == 'name'">
              <div @click="openCustomerTab(scope.row.id)" :class="[ globalIsHaveCustomerViewDetailAuth ? 'view-detail-btn' : 'view-detail-btn-disabled']">{{ scope.row[column.field] }}</div>
            </template>
           
            <template v-else-if="column.field === 'customerAddress'">
                {{formatAddress(scope.row[column.field])}}
            </template>
            <template v-else-if="column.field === 'detailAddress'">
              {{scope.row.customerAddress && scope.row.customerAddress.adAddress}}
            </template>
            <template v-else-if="column.field === 'createUser'">
              <template v-if="isOpenData">
                <open-data type='userName' :openid="scope.row.createUserStaffId"></open-data>
              </template>
              <template v-else>
                <span v-if="scope.row.createUserName">{{ scope.row.createUserName}} </span>
                <span v-else-if="scope.row.createLoginUser">{{ scope.row.createLoginUser.displayName || ''}} </span>
              </template>
            </template>
            <template v-else>
              {{ $formatFormField(column, scope.row) }}
            </template> 
          </template>
        </el-table-column>
      </el-table>
      <div class="merge-customer-item last-item"  v-if="pageType=='detail'">
        <label>{{$t('customer.mergeCustomer.step2')}}</label>
        <el-select 
          v-model="needMergeCustomerId" 
          filterable
          :placeholder="$t('common.placeholder.selectCountry')"
        >
          <el-option
            v-for="item in selectedCustomers"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{ $t('common.base.cancel') }}</el-button>
      <el-button type="primary" @click="onSubmit" :disabled="pending">{{ $t('common.base.confirm') }}</el-button>
    </div>
  </base-modal>
</template>
<script>
/** utils */
import { isOpenData, openAccurateTab } from '@src/util/platform'
import { getFixedColumns } from '../fields';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import AuthMixin from '@src/mixins/authMixin'
import { formatAddress } from 'pub-bbx-utils';

/** api */
import { getCustomerList, mergeCustomers } from '@src/api/CustomerApi';
export default {
  name: 'merge-customer-dialog',
  mixins: [
    AuthMixin,
  ],
  props: {
    currentCustomer: {
      type: Object,
      default: ()=>({}),
    },
    pageType: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      formatAddress,
      isOpenData,
      customerField: {
        isSystem: 1,
        fieldName: 'customer',
        displayName: this.$t('common.base.product'),
        formType: 'customer',
        defaultValue: null,
        isNull: 0,
        isSearch: 0,
        placeHolder: null,
      },
      needMergeCustomerId:'', // 需要合并的客户id
      pending: false,
      visible: false,
      radioIndex: 0,
      selectedCustomers: []
    };
  },
  computed: {
    columns() {
      const filterField = ['name', 'serialNumber', 'lmName', 'lmPhone','customerAddress', 'detailAddress', 'createTime','createUser']
      return getFixedColumns().filter(item=> filterField.includes(item.fieldName))
    },
  },
  methods: {
    /**打开客户详情 */
    openCustomerTab(customerId) {
      if (!this.globalIsHaveCustomerViewDetailAuth) return

      let fromId = window.frameElement.getAttribute('id');

      openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomerView,
        key: customerId,
        fromId,
        reload: true,
      })
    },
    /** 选择需要合并的数据 */
    handleRadioChange(index, row) {
      this.radioIndex = index;
      this.needMergeCustomerId = row.id;
    },
    /**打开弹窗 */
    open() {
      this.visible = true;
      
      if(this.pageType == 'detail'){
        this.needMergeCustomerId = this.currentCustomer?.id ?? '';
        this.selectedCustomers = this.selectedCustomers.map(customer =>
          Object.freeze({
            label: customer.name,
            value: customer.id,
            ...customer,
          })
        );
      }else {
        this.radioIndex = 0;
        this.needMergeCustomerId = this.selectedCustomers?.[0]?.id ?? '';
      }
    },
    /** 提交合并客户 */
    async onSubmit() {
      try {
        if(this.selectedCustomers?.length < 2) return this.$message.warning(this.$t('customer.mergeCustomer.msg1'));
       
        const confirm = await this.$confirm(this.$t('customer.mergeCustomer.msg5'),this.$t('customer.mergeCustomer.msg6'),{ confirmButtonText: this.$t('common.base.confirm'), cancelButtonText: this.$t('common.base.cancel')}).catch(() => {});
        if (!confirm) return;

        this.pending = true;
        const params = {
          newCustomerId: this.needMergeCustomerId,
          oldCustomerId: this.selectedCustomers.map(customer=> customer.id)
        }
        const { success, message } = await mergeCustomers(params)
        if(!success) return this.$message.warning(message);

        this.$message.success(this.$t('customer.mergeCustomer.msg4'));
        this.visible = false;
        
        setTimeout(() => {
          this.$emit('saveSuccess')
        }, 1000);
        
      }catch(error) {
        console.log(error)
      } finally{
        this.pending = false
      }
    },
    /**更新客户信息 */
    updateCustomer(val) {
      if(val?.length == 0) {
        const currentSelect = {
          label: this.currentCustomer.name,
          value:  this.currentCustomer.id,
          ...this.currentCustomer,
        }
        this.selectedCustomers.push(currentSelect);
      }
      const currentCustomerId = this.currentCustomer?.id;
      const currentCustomerIndex = val.findIndex(item => item.id === currentCustomerId);

      if (currentCustomerIndex !== -1) {
          const [currentCustomer] = val.splice(currentCustomerIndex, 1);
          val.unshift(currentCustomer);
          this.selectedCustomers = val;
          this.$emit('updateCustomer', val);
      }
      // 如果主客户不存在清空
      if(!val.some(item=> item.id == this.needMergeCustomerId)) {
        this.needMergeCustomerId = this.selectedCustomers?.[0]?.id  || ''
      }
    },
    /**搜索客户 */
    async searchCustomer(params) {
      try {
        const pms = params || {};
        const res = await getCustomerList(pms);

        if (!res || !res.list) return;

        res.list = res.list.map(customer => {
          if (customer.id === this.currentCustomer?.id && this.pageType === 'detail') {
            customer.disabled = true;
          }
          return Object.freeze({
            label: customer.name,
            value: customer.id,
            ...customer,
          });
        });

        return res;
      } catch (e) {
        console.error(e);
      }
    }
  },
};
</script>
<style lang="scss" scoped>
.merge-customer-dialog {
  .merge-customer-wrap {
    .message {
        font-size: 14px;
        height: 38px;
        line-height: 38px;
        color: $text-color-regular;
        background: #F4F4F5;
        border-radius: 4px;
        text-indent: 16px;
        margin: 0 0 16px 0;
    }
    .customer-select-table {
      border: 1px solid #EBEEF5;
      border-bottom: none;
      ::v-deep .el-radio__label {
        display: none;
      }
    }
  }
  .merge-customer-item {
    margin-bottom: 16px;
    label {
      margin-bottom: 6px;
    }
    .el-select {
      width: 100%
    }
  }
}
.last-item {
  margin-top: 16px;
}
.customer-template-option {
  * {
    margin: 0;
  }
  padding: 10px 0;
  h3 {
    font-size: 14px;
    font-weight: 500;
    line-height: 24px;
  }

  p {
    line-height: 24px;
    font-size: 12px;
    padding-right: 10px;

    & > span {
      width: 100%;
      display: flex;
      justify-content: flex-start;
      flex: 1;
      font-size: 12px;
      padding-right: 10px;
    }
  }
}
.custom-select {
  ::v-deep .el-select {
    .el-select__tags span:first-child.el-tag {
      .el-tag__close.el-icon-close {
        display: none !important;
      }
    }
  }
}

</style>